package com.lkpstudy.rbac.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkpstudy.rbac.entity.Auth;
import com.lkpstudy.rbac.entity.Role;
import com.lkpstudy.rbac.entity.User;
import com.lkpstudy.rbac.service.UserService;
import com.lkpstudy.rbac.mapper.UserMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
* @author likaiping
* @description 针对表【user(系统用户)】的数据库操作Service实现
* @createDate 2024-04-17 20:25:23
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Override
    public List<Role> findRoles(String username) {
        if (Objects.isNull(username)) {
            throw new RuntimeException("用户名不能为空");
        }
        Long userId = baseMapper.selectIdByUsername(username);
        if (Objects.isNull(userId)) {
            throw new RuntimeException("用户不存在");
        }
        return baseMapper.listRolesByUserId(userId);
    }

    @Override
    public List<Auth> findAuths(String username) {
        if (Objects.isNull(username)) {
            throw new RuntimeException("用户名不能为空");
        }
        Long userId = baseMapper.selectIdByUsername(username);
        if (Objects.isNull(userId)) {
            throw new RuntimeException("用户不存在");
        }
        List<Long> roleIds = baseMapper.listRolesIdsByUserId(userId);
        if (Objects.isNull(roleIds)) {
            throw new RuntimeException("当前用户没有角色");
        }
        return baseMapper.listAuthsByRoleIds(roleIds);
    }

    @Override
    public boolean editRoles(String username, List<Long> roleIds) {
        if (Objects.isNull(username)) {
            throw new RuntimeException("用户名不能为空");
        }
        if (Objects.isNull(roleIds) || roleIds.size() == 0) {
            throw new RuntimeException("没有需要修改的角色");
        }
        Long userId = baseMapper.selectIdByUsername(username);
        if (Objects.isNull(userId)) {
            throw new RuntimeException("用户不存在");
        }
        baseMapper.deleteRolesByUserId(userId);
        baseMapper.insertRolesBatch(userId,roleIds);

        return true;
    }
}




